package com.example.chartroom.controller;

import com.example.chartroom.component.OnlineUserManager;
import com.example.chartroom.model.AddFriendRequest;
import com.example.chartroom.model.Friend;
import com.example.chartroom.model.FriendMapper;
import com.example.chartroom.model.User;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.w3c.dom.UserDataHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.security.cert.CertPathValidatorException;
import java.util.ArrayList;
import java.util.List;

@RestController
public class FriendController {
    @Autowired
    private FriendMapper friendMapper;
    @Autowired
    private OnlineUserManager onlineUserManager;
    private ObjectMapper objectMapper;
    @GetMapping("/friendList")
    public Object getFriendList(HttpServletRequest req){
        HttpSession session = req.getSession(false);
        if(session == null){
            System.out.println("[getFriendList] session 不存在");
            return new ArrayList<Friend>();
        }
        User user = (User) session.getAttribute("user");
        if(user == null){
            System.out.println("[getFriend] user 不存在");
            return new ArrayList<Friend>();
        }
        List<Friend> friendList = friendMapper.selectFriendList(user.getUserId());
        return friendList;
    }
    @GetMapping("/findFriend")
    @ResponseBody
    public Object finFriend(String name,HttpServletRequest rep){
        try {
            //需要根据当前的用户的ID排除自己和已有的用户
            HttpSession session= rep.getSession(false);
            User user = (User) session.getAttribute("user");
            return friendMapper.findFriend(user.getUserId(),name);

        }catch (NullPointerException e){
            e.printStackTrace();
        }
        return "";
    }

    @GetMapping("/addFriend")
    public Object addFriend(int friendId,String reason,HttpServletRequest req){
        try {
            HttpSession session = req.getSession(false);
            User user = (User) session.getAttribute("user");
            System.out.println("[添加好友] "+user.getUserId()+","+friendId +","+reason );
            //写入到数据库
            friendMapper.addFriendRequest(user.getUserId(),friendId,reason);
            //发送WebSocket响应
            WebSocketSession webSocketSession = onlineUserManager.getSession(friendId);
            if(webSocketSession != null){
                AddFriendRequest addFriendRequest = new AddFriendRequest();
                addFriendRequest.setType("addFriendRequest");
                addFriendRequest.setFromUserId(user.getUserId());
                addFriendRequest.setFromUserName(user.getUsername());
                addFriendRequest.setReason(reason);
                //给对应的用户发送WebScoket请求,提示有用户尝试加好友
                webSocketSession.sendMessage(new TextMessage(objectMapper.writeValueAsString(addFriendRequest)));

            }
        }catch (Exception e){
            e.printStackTrace();

        }
        return "";
    }
    @GetMapping("/getFriendRequest")
    public Object getFriendRequest(HttpServletRequest req){
        List<AddFriendRequest> addFriendRequestList = new ArrayList<>();
        try {
            HttpSession session = req.getSession(false);
            User user = (User) session.getAttribute("user");
            addFriendRequestList = friendMapper.getFriendRequest(user.getUserId());
        }catch (NullPointerException e){
            e.printStackTrace();
        }
        return addFriendRequestList;
    }
    @GetMapping("/acceptFriend")
    //此处需要多次操作数据库, 因此使⽤事务保证原⼦性
    @Transactional
    public Object accpetFrined(int friendId,HttpServletRequest req){
        try {
            HttpSession session = req.getSession(false);
            User user = (User) session.getAttribute("user");
            //1.删除好友请求表的存档
            friendMapper.deleteFriendRequest(friendId,user.getUserId());
            //2.修改好友表
            friendMapper.addFriend(friendId,user.getUserId());
            WebSocketSession webSocketSession = onlineUserManager.getSession(friendId);
            if(webSocketSession != null){
                AddFriendRequest addFriendRequest = new AddFriendRequest();
                addFriendRequest.setType("acceptFriend");
                addFriendRequest.setFromUserId(user.getUserId());
                addFriendRequest.setFromUserName(user.getUsername());
                addFriendRequest.setReason("");
                webSocketSession.sendMessage(new TextMessage(objectMapper.writeValueAsString(addFriendRequest)));
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }
    @GetMapping("/rejectFriend")
    public Object rejectFriend(int friendId,HttpServletRequest req){
        try{
            HttpSession session = req.getSession(false);
            User user = (User) session.getAttribute("user");
            //删除好友请求表的档
            friendMapper.deleteFriendRequest(friendId,user.getUserId());
        }catch (NullPointerException e){
            e.printStackTrace();
        }
        return "";
    }
}
